﻿using System;
using System.Threading.Tasks;
using JT808.Gateway.Abstractions;
using JT808.Gateway.Kafka;
using JT808.Gateway.QueueServer.Custom;
using JT808.Gateway.RabbitMQ;
using JT808.Gateway.Session;
using JT808.Protocol;
using JT808.Protocol.Enums;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace JT808.Gateway.QueueServer
{
    public static class JT808ServerExtensions
    {
        public static ValueTask<JT808Package> TrySendPackageAndWaitAsync(this JT808SessionManager sessionManager, string terminalPhoneNo, in JT808Package package, JT808Serializer serializer, JT808Version version)
        {
            if (sessionManager.TrySendPackageAsync(terminalPhoneNo, package, serializer, version).Result)
                return sessionManager.WaitReplyMessageBySn(terminalPhoneNo, package.Header, new TimeSpan(0, 0, 1));
            return default;
        }

        public static ValueTask<bool> TrySendPackageAsync(this JT808SessionManager sessionManager, string terminalPhoneNo, in JT808Package package, in JT808Serializer serializer, JT808Version version)
        {
            byte[] data = serializer.Serialize(package, version);
            return sessionManager.TrySendByTerminalPhoneNoAsync(terminalPhoneNo, data);
        }

        public static IJT808GatewayBuilder AddRabbitApiResponseService(this IJT808GatewayBuilder builder, IConfiguration configuration)
        {
            builder.JT808Builder.Services.AddHostedService<JT808ApiResponseHostedService>();
            builder.AddServerRabbitResponseConsumer(configuration);
            return builder;
        }
        public static IJT808GatewayBuilder AddKafkaApiResponseService(this IJT808GatewayBuilder builder, IConfiguration configuration)
        {
            builder.JT808Builder.Services.AddHostedService<JT808ApiResponseHostedService>();
            builder.AddServerKafkaResponseConsumer(configuration);
            return builder;
        }
    }
}
